/**
 * Created by TRwin7SP1 on 2016/8/10.
 */

$(document).ready(function() {

    var imageIds = [
        'example://1',
        'example://2'];
    var currentImageIndex = 0;


    // updates the image display
    function updateTheImage(imageIndex) {
        return cornerstone.loadAndCacheImage(imageIds[imageIndex]).then(function(image) {
            currentImageIndex = imageIndex;
            var viewport = cornerstone.getViewport(element);
            cornerstone.displayImage(element, image, viewport);
        });
    }

    // image enable the element
    var element = $('#dicomImage').get(0);
    cornerstone.enable(element);

    // set event handlers
    function onImageRendered(e, eventData) {
        $('#topright').text("Render Time:" + eventData.renderTimeInMs + " ms");
    }
    $(element).on("CornerstoneImageRendered", onImageRendered);

    // setup handlers before we display the image
    function onImageRendered(e, eventData) {
        // set the canvas context to the image coordinate system
        cornerstone.setToPixelCoordinateSystem(eventData.enabledElement, eventData.canvasContext);

        // NOTE: The coordinate system of the canvas is in image pixel space.  Drawing
        // to location 0,0 will be the top left of the image and rows,columns is the bottom
        // right.
        var context = eventData.canvasContext;
        context.beginPath();
        context.strokeStyle = 'white';
        context.lineWidth = .5;
        context.rect(128, 90, 50, 60);
        context.stroke();
        context.fillStyle = "white";
        context.font = "6px Arial";
        context.fillText("Tumor Here", 128, 85);

        $('#topright').text("Render Time:" + cornerstone.lastRenderTimeInMs + " ms");
        $('#bottomleft').text("WW/WL:" + Math.round(eventData.viewport.voi.windowWidth) + "/" + Math.round(eventData.viewport.voi.windowCenter));
        $('#bottomright').text("Zoom:" + eventData.viewport.scale.toFixed(2));

    }
    $(element).on("CornerstoneImageRendered", onImageRendered);

    // load and display the image
    var imagePromise = updateTheImage(0);

    // add handlers for mouse events once the image is loaded.
    imagePromise.then(function() {
        viewport = cornerstone.getViewport(element);
        $('#bottomright').text("Zoom: " + viewport.scale.toFixed(2) + "x");
        $('#bottomleft').text("WW/WC:" + Math.round(viewport.voi.windowWidth) + "/" + Math.round(viewport.voi.windowCenter));

        // add event handlers to pan image on mouse move
        $('#dicomImage').mousedown(function (e) {
            var lastX = e.pageX;
            var lastY = e.pageY;

            var mouseButton = e.which;

            $(document).mousemove(function (e) {
                var deltaX = e.pageX - lastX,
                    deltaY = e.pageY - lastY;
                lastX = e.pageX;
                lastY = e.pageY;

                if (mouseButton == 1) {
                    var viewport = cornerstone.getViewport(element);
                    viewport.voi.windowWidth += (deltaX / viewport.scale);
                    viewport.voi.windowCenter += (deltaY / viewport.scale);
                    cornerstone.setViewport(element, viewport);
                    $('#bottomleft').text("WW/WL:" + Math.round(viewport.voi.windowWidth) + "/" + Math.round(viewport.voi.windowCenter));
                }
                else if (mouseButton == 2) {
                    var viewport = cornerstone.getViewport(element);
                    viewport.translation.x += (deltaX / viewport.scale);
                    viewport.translation.y += (deltaY / viewport.scale);
                    cornerstone.setViewport(element, viewport);
                }
                else if (mouseButton == 3) {
                    var viewport = cornerstone.getViewport(element);
                    viewport.scale += (deltaY / 100);
                    cornerstone.setViewport(element, viewport);
                    $('#bottomright').text("Zoom: " + viewport.scale.toFixed(2) + "x");
                }
            });

            $(document).mouseup(function (e) {
                $(document).unbind('mousemove');
                $(document).unbind('mouseup');
            });
        });

        $('#dicomImage').on('mousewheel DOMMouseScroll', function (e) {
            // Firefox e.originalEvent.detail > 0 scroll back, < 0 scroll forward
            // chrome/safari e.originalEvent.wheelDelta < 0 scroll back, > 0 scroll forward
            if (e.originalEvent.wheelDelta < 0 || e.originalEvent.detail > 0) {
                if (currentImageIndex == 0) {
                    updateTheImage(1);
                }
            } else {
                if (currentImageIndex == 1) {
                    updateTheImage(0);
                }
            }
            //prevent page fom scrolling
            return false;
        });

        // Add event handler to the ww/wc apply button
        $('#x256').click(function (e) {
            $('#dicomImage').width(256).height(256);
            $('#dicomImageWrapper').width(256).height(256);
            cornerstone.resize(element);
        });

        $('#x512').click(function (e) {
            $('#dicomImage').width(512).height(512);
            $('#dicomImageWrapper').width(512).height(512);
            cornerstone.resize(element);
        });

        $('#invert').click(function (e) {
            var viewport = cornerstone.getViewport(element);
            if (viewport.invert === true) {
                viewport.invert = false;
            } else {
                viewport.invert = true;
            }
            cornerstone.setViewport(element, viewport);
        });

        $('#interpolation').click(function (e) {
            var viewport = cornerstone.getViewport(element);
            if (viewport.pixelReplication === true) {
                viewport.pixelReplication = false;
            } else {
                viewport.pixelReplication = true;
            }
            cornerstone.setViewport(element, viewport);
        });
        $('#hflip').click(function (e) {
            var viewport = cornerstone.getViewport(element);
            viewport.hflip = !viewport.hflip;
            cornerstone.setViewport(element, viewport);
        });
        $('#vflip').click(function (e) {
            var viewport = cornerstone.getViewport(element);
            viewport.vflip = !viewport.vflip;
            cornerstone.setViewport(element, viewport);
        });
        $('#rotate').click(function (e) {
            var viewport = cornerstone.getViewport(element);
            viewport.rotation+=90;
            cornerstone.setViewport(element, viewport);
        });
        $(element).mousemove(function(event)
        {
            var pixelCoords = cornerstone.pageToPixel(element, event.pageX, event.pageY);
            var x = event.pageX;
            var y = event.pageY;
            $('#coords').text("pageX=" + event.pageX + ", pageY=" + event.pageY + ", pixelX=" + pixelCoords.x + ", pixelY=" + pixelCoords.y);
        });
    });



});
